﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using System.Configuration;
using System.Net;
using System.IO;
using System.Text;
using Microsoft.AspNet.SignalR;

namespace Derrick.Web
{
    public sealed class TwitterStream : IDisposable
    {
        private static volatile TwitterStream _twitterStream;
        private static object _lockObject = new object();
        private Thread _twitterListener = null;

        private TwitterStream()
        {
            _twitterListener = new Thread(new ThreadStart(getTwitterStream));
            _twitterListener.Start();
        }

        public static TwitterStream Instance
        {
            get
            {
                if (null == _twitterStream)
                {
                    lock (_lockObject)
                    {
                        if (null == _twitterStream)
                        {
                            _twitterStream = new TwitterStream();
                        }
                    }
                }
                return _twitterStream;
            }
        }

        private void getTwitterStream()
        {
            string twitterStreamingUrl = ConfigurationManager.AppSettings["TwitterStreamingUrl"];
            string twitterUsername = ConfigurationManager.AppSettings["TwitterUsername"];
            string twitterPassword = ConfigurationManager.AppSettings["TwitterPassword"];

            WebRequest twitterRequest = WebRequest.Create(twitterStreamingUrl);
            twitterRequest.Method = "POST";
            twitterRequest.ContentType = "application/json";
            twitterRequest.Credentials = new NetworkCredential(twitterUsername, twitterPassword);
            Stream twitterRequestContent = twitterRequest.GetRequestStream();
            Encoding encode = Encoding.GetEncoding("utf-8");

            StreamWriter twitterWriter = new StreamWriter(twitterRequestContent);


            WebResponse twitterResponse = twitterRequest.GetResponse();


            StreamReader twitterStream = new StreamReader(twitterResponse.GetResponseStream(), encode);

            IHubContext twitterHub = GlobalHost.ConnectionManager.GetHubContext<TwitterHub>();

            while (!twitterStream.EndOfStream)
            {
                string twitterMessage = twitterStream.ReadLine();
                //do something with twitterMessage...
                twitterMessage = twitterMessage.Trim();
                if (!String.IsNullOrEmpty(twitterMessage))
                {
                    twitterHub.Clients.All.broadcastTweet(twitterMessage);
                }
            }

        }


        public void Dispose()
        {
            //throw new NotImplementedException();
            _twitterListener.Abort();
        }

        public void Initialize()
        {

        }
    }
}